package com.agger.harmonyosthemeseditor.abilities;

import com.agger.harmonyosthemeseditor.ResourceTable;
import com.agger.harmonyosthemeseditor.intelligent.DatabaseManager;
import com.agger.harmonyosthemeseditor.intelligent.FileManager;
import com.agger.harmonyosthemeseditor.intelligent.GeneralUtil;
import com.agger.harmonyosthemeseditor.intelligent.ZipFileTool;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.event.notification.NotificationHelper;
import ohos.event.notification.NotificationRequest;
import ohos.event.notification.NotificationSlot;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.media.image.PixelMap;
import ohos.rpc.IRemoteObject;
import ohos.rpc.RemoteException;

import java.io.File;
import java.io.FileOutputStream;

public class PreloadServiceAbility extends Ability
{
    private static final int CACHE_SIZE = 256 * 1024;
    public static String AGI_IntelligentNotification_Name = "爱洁羊智慧能力";
    public static String AGI_IntelligentNotification_Slot_LoadAGITemplate = "加载支持库";
    public static String AGI_IntelligentNotification_PreloadTemplate_KeepRunning = "“主题协作器”正在后台运行";
    public static String AGI_IntelligentNotification_PreloadTemplate_Start = "正在准备必要的支持库，请不要强制结束当前进程！";
    public static String AGI_IntelligentNotification_PreloadTemplate_Ready = "基础支持库准备就绪，开始部署主题协作环境！";
    public static String AGI_IntelligentNotification_PreloadTemplate_Finish = "主题协作环境搭建完成，感谢您的支持！";
    public static String AGI_IntelligentNotification_PreloadTemplate_DeployFailed_File = "基础支持库准备失败，可能是设备没有足够的存储空间，或资源被其它进程占用！建议您结束第三方可疑进程，并确保设备容量充足，然后重启您的设备，再次进入主题协作器~";
    public static String AGI_IntelligentNotification_PreloadTemplate_DeployFailed_Cache = "主题协作环境搭建失败，可能是设备没有足够的存储空间，或资源被其它进程占用！建议您结束第三方可疑进程，并确保设备容量充足，然后重启您的设备，再次进入主题协作器~";
    public static boolean isTemplateFileReady = false;
    public static PixelMap pxm;
    public static boolean isRunning = false;
    public static boolean isFinished = false;
    public static boolean isSuccess = false;

    private class MyEventHandler extends EventHandler
    {
        private MyEventHandler(EventRunner runner) {
            super(runner);
        }
        @Override
        public void processEvent(InnerEvent event)
        {
            super.processEvent(event);
            if (event == null) { return; }
            LoadAGITemplate();
            cancelBackgroundRunning();
            isFinished = true;
            try{terminateAbility();}catch(Exception ex){}
        }
    }

    @Override
    public void onStart(Intent intent)
    {
        super.onStart(intent);
        if(!isRunning)
        {
            isRunning = true;
            isFinished = false;
            isSuccess = false;
            ohos.global.resource.ResourceManager resManager = getContext().getResourceManager();
            try
            {
                AGI_IntelligentNotification_Name = resManager.getElement(ResourceTable.String_AGI_IntelligentNotification_Name).getString();
                AGI_IntelligentNotification_Slot_LoadAGITemplate = resManager.getElement(ResourceTable.String_AGI_IntelligentNotification_Slot_LoadAGITemplate).getString();
                AGI_IntelligentNotification_PreloadTemplate_KeepRunning = resManager.getElement(ResourceTable.String_AGI_IntelligentNotification_PreloadTemplate_KeepRunning).getString();
                AGI_IntelligentNotification_PreloadTemplate_Start = resManager.getElement(ResourceTable.String_AGI_IntelligentNotification_PreloadTemplate_Start).getString();
                AGI_IntelligentNotification_PreloadTemplate_Ready = resManager.getElement(ResourceTable.String_AGI_IntelligentNotification_PreloadTemplate_Ready).getString();
                AGI_IntelligentNotification_PreloadTemplate_Finish = resManager.getElement(ResourceTable.String_AGI_IntelligentNotification_PreloadTemplate_Finish).getString();
                AGI_IntelligentNotification_PreloadTemplate_DeployFailed_File = resManager.getElement(ResourceTable.String_AGI_IntelligentNotification_PreloadTemplate_DeployFailed_File).getString();
                AGI_IntelligentNotification_PreloadTemplate_DeployFailed_Cache = resManager.getElement(ResourceTable.String_AGI_IntelligentNotification_PreloadTemplate_DeployFailed_Cache).getString();
            }catch (Exception e){e.printStackTrace();}
            NotificationSlot slot = new NotificationSlot("LoadAGITemplate", AGI_IntelligentNotification_Slot_LoadAGITemplate, NotificationSlot.LEVEL_HIGH);
            slot.setEnableVibration(false);
            try {NotificationHelper.addNotificationSlot(slot);} catch (RemoteException ex) {ex.printStackTrace();}
            pxm = GeneralUtil.getPixelMapFromResource(this,ResourceTable.Media_NotificationIcon);
            NotificationRequest request = new NotificationRequest(1001);
            NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
            content.setTitle(AGI_IntelligentNotification_Name).setText(AGI_IntelligentNotification_PreloadTemplate_KeepRunning);
            NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
            request.setContent(notificationContent).setSlotId("LoadAGITemplate").setLittleIcon(pxm);
            keepBackgroundRunning(1001, request);
            EventRunner runner = EventRunner.create(true);
            MyEventHandler myHandler = new MyEventHandler(runner);
            myHandler.sendEvent(0, 0, EventHandler.Priority.IMMEDIATE);
        }else
        {
            isFinished = true;
            try{terminateAbility();}catch(Exception ex){}
        }
    }

    void LoadAGITemplate()
    {
        DatabaseManager.Init(getContext());
        boolean isThemesTemplateReady = DatabaseManager.getString("isThemesTemplateReady", "false").equals("true");
        if(!isThemesTemplateReady)
        {
            NotificationRequest request_start = new NotificationRequest(1005);
            NotificationRequest.NotificationLongTextContent content_start = new NotificationRequest.NotificationLongTextContent();
            content_start.setTitle(AGI_IntelligentNotification_Name).setLongText(AGI_IntelligentNotification_PreloadTemplate_Start);
            NotificationRequest.NotificationContent notificationContent_start = new NotificationRequest.NotificationContent(content_start);
            request_start.setContent(notificationContent_start).setSlotId("LoadAGITemplate").setLittleIcon(pxm);
            try{NotificationHelper.publishNotification(request_start);}catch(RemoteException ex){ex.printStackTrace();}
            writeToFilesDir(getContext().getFilesDir()+"/ThemesTemplate.zip");
            try{NotificationHelper.cancelNotification(1005);}catch(RemoteException ex){ex.printStackTrace();}
            if(!isTemplateFileReady)
            {
                NotificationRequest request_DeployFailed_File = new NotificationRequest(1004);
                NotificationRequest.NotificationLongTextContent content_DeployFailed_File = new NotificationRequest.NotificationLongTextContent();
                content_DeployFailed_File.setTitle(AGI_IntelligentNotification_Name).setLongText(AGI_IntelligentNotification_PreloadTemplate_DeployFailed_File);
                NotificationRequest.NotificationContent notificationContent_DeployFailed_File = new NotificationRequest.NotificationContent(content_DeployFailed_File);
                request_DeployFailed_File.setContent(notificationContent_DeployFailed_File).setSlotId("LoadAGITemplate").setLittleIcon(pxm);
                try{NotificationHelper.publishNotification(request_DeployFailed_File);}catch(RemoteException ex){ex.printStackTrace();}
                DatabaseManager.setString("isThemesTemplateReady","false");
                return;
            }
        }

        boolean isThemesTemplateDeployed = DatabaseManager.getString("isThemesTemplateDeployed", "false").equals("true");
        String ThemesTemplateCachePath = getFilesDir()+"/ThemesTemplate/";
        File ThemesTemplateCachePathFile = new File(ThemesTemplateCachePath);
        if(!ThemesTemplateCachePathFile.exists())
        {
            isThemesTemplateDeployed = false;
            DatabaseManager.setString("isThemesTemplateDeployed","false");
        }

        if(!isThemesTemplateDeployed)
        {
            NotificationRequest request_ready = new NotificationRequest(1006);
            NotificationRequest.NotificationLongTextContent content_ready = new NotificationRequest.NotificationLongTextContent();
            content_ready.setTitle(AGI_IntelligentNotification_Name).setLongText(AGI_IntelligentNotification_PreloadTemplate_Ready);
            NotificationRequest.NotificationContent notificationContent_ready = new NotificationRequest.NotificationContent(content_ready);
            request_ready.setContent(notificationContent_ready).setSlotId("LoadAGITemplate").setLittleIcon(pxm);
            try{NotificationHelper.publishNotification(request_ready);}catch(RemoteException ex){ex.printStackTrace();}
            try
            {
                if(ThemesTemplateCachePathFile.exists())
                {
                    FileManager.deleteDirectory(ThemesTemplateCachePath);
                }
                isSuccess = ZipFileTool.unzip(getContext().getFilesDir()+"/ThemesTemplate.zip",ThemesTemplateCachePath);
                if(isSuccess)
                {
                    DatabaseManager.setString("isThemesTemplateDeployed", "true");
                    try {NotificationHelper.cancelNotification(1006);} catch (RemoteException ex) {ex.printStackTrace();}
                    NotificationRequest request_finish = new NotificationRequest(1007);
                    NotificationRequest.NotificationLongTextContent content_finish = new NotificationRequest.NotificationLongTextContent();
                    content_finish.setTitle(AGI_IntelligentNotification_Name).setLongText(AGI_IntelligentNotification_PreloadTemplate_Finish);
                    NotificationRequest.NotificationContent notificationContent_finish = new NotificationRequest.NotificationContent(content_finish);
                    request_finish.setContent(notificationContent_finish).setSlotId("LoadAGITemplate").setLittleIcon(pxm);
                    try {NotificationHelper.publishNotification(request_finish);} catch (RemoteException ex) {ex.printStackTrace();}
                }else
                {
                    try{NotificationHelper.cancelNotification(1006);}catch(RemoteException ex){ex.printStackTrace();}
                    DatabaseManager.setString("isThemesTemplateDeployed","false");
                    NotificationRequest request_DeployFailed_Cache = new NotificationRequest(1003);
                    NotificationRequest.NotificationLongTextContent content_DeployFailed_Cache = new NotificationRequest.NotificationLongTextContent();
                    content_DeployFailed_Cache.setTitle(AGI_IntelligentNotification_Name).setLongText(AGI_IntelligentNotification_PreloadTemplate_DeployFailed_Cache);
                    NotificationRequest.NotificationContent notificationContent_DeployFailed_Cache = new NotificationRequest.NotificationContent(content_DeployFailed_Cache);
                    request_DeployFailed_Cache.setContent(notificationContent_DeployFailed_Cache).setSlotId("LoadAGITemplate").setLittleIcon(pxm);
                    try{NotificationHelper.publishNotification(request_DeployFailed_Cache);}catch(RemoteException ex){ex.printStackTrace();}
                    return;
                }
            }
            catch (Exception e)
            {
                try{NotificationHelper.cancelNotification(1006);}catch(RemoteException ex){ex.printStackTrace();}
                DatabaseManager.setString("isThemesTemplateDeployed","false");
                NotificationRequest request_DeployFailed_Cache = new NotificationRequest(1003);
                NotificationRequest.NotificationLongTextContent content_DeployFailed_Cache = new NotificationRequest.NotificationLongTextContent();
                content_DeployFailed_Cache.setTitle(AGI_IntelligentNotification_Name).setLongText(AGI_IntelligentNotification_PreloadTemplate_DeployFailed_Cache);
                NotificationRequest.NotificationContent notificationContent_DeployFailed_Cache = new NotificationRequest.NotificationContent(content_DeployFailed_Cache);
                request_DeployFailed_Cache.setContent(notificationContent_DeployFailed_Cache).setSlotId("LoadAGITemplate").setLittleIcon(pxm);
                try{NotificationHelper.publishNotification(request_DeployFailed_Cache);}catch(RemoteException ex){ex.printStackTrace();}
                return;
            }
        }else
        {
            isSuccess = true;
        }
    }

    private void writeToFilesDir(String targetFilePath)
    {
        RawFileEntry rawFileEntry = getResourceManager().getRawFileEntry("entry/resources/rawfile/ThemesTemplate.zip");
        File targetFile = new File(targetFilePath);
        if(targetFile.exists()) targetFile.delete();
        try(FileOutputStream output = new FileOutputStream(targetFilePath))
        {
            Resource resource = rawFileEntry.openRawFile();
            byte[] cache = new byte[CACHE_SIZE];
            int len = resource.read(cache);
            while (len != -1)
            {
                output.write(cache, 0, len);
                len = resource.read(cache);
            }
            isTemplateFileReady = true;
            DatabaseManager.setString("isThemesTemplateReady","true");
        }catch(Exception e){isTemplateFileReady = false;}
    }

    @Override
    public void onBackground() {
        super.onBackground();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onCommand(Intent intent, boolean restart, int startId) { }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        return null;
    }

    @Override
    public void onDisconnect(Intent intent) { }
}